﻿using System;
using System.Diagnostics.CodeAnalysis;
using BootstrapBlazor.Components;
using iTeamyou.LTS.Core.Services;
using iTeamyou.LTS.Core.Models;
using Microsoft.AspNetCore.Components;
using NPOI.XWPF.UserModel;
using System.Linq;
using iTeamyou.LTS.UI.Utils;
using iTeamyou.LTS.UI.Models;
using System.Reflection.Emit;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Newtonsoft.Json.Linq;
using NPOI.SS.Formula.Functions;
using NPOI.HPSF;
using System.IO;
using NPOI.OpenXmlFormats.Wordprocessing;

namespace iTeamyou.LTS.UI.Pages.Archive.License
{
	public partial class Index
	{
        [Parameter]
        public string? Token { get; set; }

		[Inject]
		[NotNull]
		private SharedService? SharedService { get; set; }

        [Inject]
        [NotNull]
        private ProductService? ProductService { get; set; }

        [Inject]
        [NotNull]
        private SupplierService? SupplierService { get; set; }

        [Inject]
        [NotNull]
        private ManufacturerService? ManufacturerService { get; set; }

        [Inject]
        [NotNull]
        private BatchService? BatchService { get; set; }

        [Inject]
        [NotNull]
        private DialogService? DialogService { get; set; }

        [Inject]
        [NotNull]
        private MessageService? MessageService { get; set; }

        [Inject]
        [NotNull]
        private NavigationManager NavigationManager { get; set; }

        [Inject]
        [NotNull]
        private DownloadService? DownloadService { get; set; }

        public List<ProductLicense>? SelectedProductLicenses { get; set; } = new();
        public List<BatchLicense>? SelectedBatchLicenses { get; set; } = new();
        public List<ManufacturerLicense>? SelectedManufacturerLicenses { get; set; } = new();
        public List<SupplierLicense>? SelectedSupplierLicenses { get; set; } = new();

        [Parameter]
        public Action? OnClose { get; set; }

        [NotNull]
        private IEnumerable<ProductLicense>? ProductLicenses { get; set; }
        private ITableSearchModel ProductSearchModel { get; set; } = new ProductSearchModel();

        [NotNull]
        private IEnumerable<SupplierLicense>? SupplierLicenses { get; set; }
        private ITableSearchModel SupplierSearchModel { get; set; } = new SupplierSearchModel();

        [NotNull]
        private IEnumerable<ManufacturerLicense>? ManufacturerLicenses { get; set; }
        private ITableSearchModel ManufacturerSearchModel { get; set; } = new ManufacturerSearchModel();

        [NotNull]
        private IEnumerable<BatchLicense>? BatchLicenses { get; set; }
        private ITableSearchModel BatchSearchModel { get; set; } = new BatchSearchModel();

        [Inject] HttpContextAccessor HttpContextAccessor { get; set; }
        [Inject] protected IExcelHelper excelHelper { get; set; }
        [Inject] protected ILoginService<LoginUser>? loginService { get; set; }

        private static IEnumerable<int> PageItemsSource => new int[] { 10, 20, 50 };
        private string UserId { get; set; }
        public bool IsAutoRefresh { get; set; }
        private bool IsUnauth { get; set; }

        public string ProductLicenseCount { get; set; }
        public string BatchLicenseCount { get; set; }
        public string ManufacturerLicenseCount { get; set; }
        public string SupplierLicenseCount { get; set; }

        private static readonly string AppCode = "LTS_License";
        private static readonly string PrivilegeCode = "[LICENSE]";

        protected override void OnInitialized()
        {
            var isDebug = bool.Parse(SharedService.GetConfig("IsDebug"));
            if (isDebug)
            {
                UserId = SharedService.GetConfig("DebugUser");
                IsUnauth = false;
            }
            else
                IsUnauth = !PageAuthAsync();

            base.OnInitialized();
            if (!IsUnauth)
            {
                SharedService.RefreshRequested += RefreshData;
                RefreshData();
            }
        }

        private bool PageAuthAsync()
        {
            var authToken = HttpContextAccessor.HttpContext.Request.Cookies["SSOToken"];

            if (!string.IsNullOrEmpty(Token))
            {
                try
                {
                    var cookieOptions = new CookieOptions()
                    {
                        Expires = DateTime.Now.AddDays(2),
                        SameSite = SameSiteMode.Strict
                    };
                    HttpContextAccessor.HttpContext.Response.Cookies.Append("SSOToken", Token, cookieOptions);
                }
                catch { }

                var segments = NavigationManager.Uri.Split('/');
                var redirectUrl = string.Join("/", segments.Take(segments.Length - 1));
                try
                {
                    NavigationManager.NavigateTo(redirectUrl, true, true);
                    Token = string.Empty;
                }
                catch (NavigationException) { }
            }
            else if (string.IsNullOrEmpty(authToken) && string.IsNullOrEmpty(Token))
            {
                try
                {
                    NavigationManager.NavigateTo(SharedService.GetConfig("EKPLoginURL"), true);
                }
                catch (NavigationException) { }
                return false;
            }

            //var authToken = "83dfa37029393dbca8047ab0482ebd1b969d4c95b11b7a1f62b6dfb529a14d5f42d8559d1467e4b5f922e95c185cc800b6ae5c2bb90ba39efb01f297c2a94b274aa99fcc6a9e6678740f3d8a2bbfd3fe77a3fd6e04c04627a729a994c218398fa4c01a440d73de4a543989eeed9c6f0ceb638d539e06375e2f967ac3dca5c1a4";
            var currentUser = loginService.Login(AppCode, authToken);

            if (currentUser == null || string.IsNullOrEmpty(currentUser.Name))
            {
                //MessageService.Show(new MessageOption()
                //{
                //    Content = $"当前用户身份无效，请联系管理员",
                //    Icon = "fa-solid fa-circle-error",
                //    Color = Color.Danger,
                //    ShowDismiss = true,
                //    IsAutoHide = false
                //});
                try
                {
                    NavigationManager.NavigateTo(SharedService.GetConfig("EKPLoginURL"), true);
                }
                catch (NavigationException) { }
                return false;
            }
            else if (string.IsNullOrEmpty(currentUser.AppCode))
            {
                MessageService.Show(new MessageOption()
                {
                    Content = $"当前用户没有注册应用，请联系管理员",
                    Icon = "fa-solid fa-circle-error",
                    Color = Color.Danger,
                    ShowDismiss = true,
                    IsAutoHide = false
                });
                return false;
            }
            else if (!currentUser.Privilege.Contains(PrivilegeCode, StringComparison.CurrentCultureIgnoreCase))
            {
                MessageService.Show(new MessageOption()
                {
                    Content = $"当前用户没有访问权限，请联系管理员",
                    Icon = "fa-solid fa-circle-error",
                    Color = Color.Danger,
                    ShowDismiss = true,
                    IsAutoHide = false
                });
                return false;
            }
            UserId = currentUser.Name;
            //HttpContextAccessor.HttpContext.Response.Cookies.Append("SSOToken", Token);
            return true;
        }

        #region 商品证照
        private async Task EditProductLicense(ProductLicense license)
        {
            var op = new DialogOption()
            {
                Title = "编辑证照",
                ShowFooter = false
            };
            op.BodyTemplate = BootstrapDynamicComponent.CreateComponent<Product.LicenseComponent>(new Dictionary<string, object?>
            {
                [nameof(Product.LicenseComponent.OnClose)] = new Action(async () => await op.CloseDialogAsync()),
                [nameof(Product.LicenseComponent.DocStatus)] = DocStatus.View,
                [nameof(Product.LicenseComponent.UserId)] = UserId,
                [nameof(Product.LicenseComponent.LicenseModel)] = license
            }).Render();
            op.IsScrolling = true;
            await DialogService.Show(op);
        }

        private async Task EditProductLicenseBtn()
        {
            var op = new DialogOption()
            {
                Title = "编辑证照",
                ShowFooter = false
            };
            op.BodyTemplate = BootstrapDynamicComponent.CreateComponent<Product.LicenseComponent>(new Dictionary<string, object?>
            {
                [nameof(Product.LicenseComponent.OnClose)] = new Action(async () => await op.CloseDialogAsync()),
                [nameof(Product.LicenseComponent.DocStatus)] = DocStatus.View,
                [nameof(Product.LicenseComponent.UserId)] = UserId,
                [nameof(Product.LicenseComponent.LicenseModel)] = SelectedProductLicenses.FirstOrDefault()
            }).Render();
            op.IsScrolling = true;
            await DialogService.Show(op);
        }

        private Task<QueryData<ProductLicense>> OnProductLicenseQueryAsync(QueryPageOptions options)
        {
            if (IsUnauth)
                return Task.FromResult(new QueryData<ProductLicense>() { });

            IsAutoRefresh = false;
            StateHasChanged();
            ProductLicenses = ProductService.GetLicenses();
            var searchModel = (ProductSearchModel)options.SearchModel;
            //var searchModel = new SearchModel();

            // 处理快速搜索条件
            if (!string.IsNullOrEmpty(options.SearchText))
                ProductLicenses = ProductLicenses.Where(i => (i.Name?.Contains(options.SearchText, StringComparison.OrdinalIgnoreCase) ?? false)
                || (i.LId?.Contains(options.SearchText, StringComparison.OrdinalIgnoreCase) ?? false));

            // 处理自定义搜索条件
            if (!string.IsNullOrEmpty(searchModel.LicenseIdOrName))
                ProductLicenses = ProductLicenses.Where(i => (i.Name?.Contains(searchModel.LicenseIdOrName, StringComparison.OrdinalIgnoreCase) ?? false)
                || (i.LId?.Contains(searchModel.LicenseIdOrName, StringComparison.OrdinalIgnoreCase) ?? false));

            if (!string.IsNullOrEmpty(searchModel.IdOrName))
            {
                var product = ProductService.GetBySKU(searchModel.IdOrName);
                if (product != null && !string.IsNullOrEmpty(product.Id))
                    ProductLicenses = ProductLicenses.Where(i => (i.ProductName?.Contains(searchModel.IdOrName, StringComparison.OrdinalIgnoreCase) ?? false)
                    || (i.ProductId?.Contains(product.Id, StringComparison.OrdinalIgnoreCase) ?? false));
                else
                    ProductLicenses = ProductLicenses.Where(i => (i.ProductName?.Contains(searchModel.IdOrName, StringComparison.OrdinalIgnoreCase) ?? false)
                    || (i.ProductId?.Contains(searchModel.IdOrName, StringComparison.OrdinalIgnoreCase) ?? false));
            }

            if (!string.IsNullOrEmpty(searchModel.Type))
                ProductLicenses = ProductLicenses.Where(i => i.Type?.Contains(searchModel.Type, StringComparison.OrdinalIgnoreCase) ?? false);


            //if (searchModel.Type != null)
            //    ProductLicenses = ProductLicenses.Where(i => i.Type == searchModel.Type);

            if (searchModel.SearchDate != null && searchModel.SearchDate.Start != null)
                ProductLicenses = ProductLicenses.Where(i => i.CreatedOn >= searchModel.SearchDate.Start && i.CreatedOn <= searchModel.SearchDate.End);

            // 过滤
            var isFiltered = false;
            if (options.Filters.Any())
            {
                ProductLicenses = ProductLicenses.Where(options.Filters.GetFilterFunc<ProductLicense>());
                isFiltered = true;
            }

            // 排序
            var isSorted = false;
            if (!string.IsNullOrEmpty(options.SortName))
            {
                if (options.SortOrder == SortOrder.Asc)
                    ProductLicenses = ProductLicenses.OrderBy(g => SharedService.GetPropertyValue(g, options.SortName));
                else if (options.SortOrder == SortOrder.Desc)
                    ProductLicenses = ProductLicenses.OrderByDescending(g => SharedService.GetPropertyValue(g, options.SortName));
                else
                    ProductLicenses = ProductLicenses.OrderByDescending(g => g.LastModifiedOn);
                isSorted = true;
            }

            // 设置记录总数
            var total = ProductLicenses.Count();

            // 内存分页
            ProductLicenses = ProductLicenses.Skip((options.PageIndex - 1) * options.PageItems).Take(options.PageItems).ToList();

            return Task.FromResult(new QueryData<ProductLicense>()
            {
                Items = ProductLicenses,
                TotalCount = total,
                IsSorted = isSorted,
                IsFiltered = isFiltered,
                IsSearch = options.CustomerSearches.Any() || !string.IsNullOrEmpty(options.SearchText),
                IsAdvanceSearch = options.CustomerSearches.Any()
            });
        }

        private async Task ExportProductLicenses()
        {
            try
            {
                var exportList = ProductService.GetLicensesExport(SelectedProductLicenses);
                exportList.ForEach(o =>
                {
                    var typeName = GetLicenseTypeName(o.Type, "product");
                    if (!string.IsNullOrEmpty(typeName))
                        o.Type = typeName;
                    o.ProductId = ProductService.Get(o.ProductId)?.PId;
                });
                var fileName = $"ProductLicense_{DateTime.Now.ToString("yyMMddHHmmss")}.xls";
                var filePathString = Path.Combine(SharedService.GetConfig("exportPath"), fileName);
                var filePath = excelHelper.ExportToExcel(exportList, "BatchLicense", filePathString, ".xls");
                using var stream = File.OpenRead(filePath);
                await DownloadService.DownloadFromStreamAsync(fileName, stream);
                await MessageService.Show(new MessageOption()
                {
                    Content = "导出成功",
                    Icon = "fa-solid fa-circle-info",
                    Color = Color.Success,
                    ShowDismiss = true
                });
            }
            catch (FileNotFoundException)
            {
                await MessageService.Show(new MessageOption()
                {
                    Content = "导出时发生错误，请重试",
                    Icon = "fa-solid fa-circle-error",
                    Color = Color.Danger,
                    ShowDismiss = true
                });
            }
        }

        private Task ProductLicenseSelectChanged(List<ProductLicense> SelectProductLicenses)
        {
            SelectedProductLicenses = SelectProductLicenses;
            StateHasChanged();
            return Task.CompletedTask;
        }

        #endregion

        #region 批次证照
        private async Task EditBatchLicense(BatchLicense license)
        {
            var op = new DialogOption()
            {
                Title = "编辑证照",
                ShowFooter = false
            };
            op.BodyTemplate = BootstrapDynamicComponent.CreateComponent<Batch.LicenseComponent>(new Dictionary<string, object?>
            {
                [nameof(Batch.LicenseComponent.OnClose)] = new Action(async () => await op.CloseDialogAsync()),
                [nameof(Batch.LicenseComponent.DocStatus)] = DocStatus.View,
                [nameof(Batch.LicenseComponent.UserId)] = UserId,
                [nameof(Batch.LicenseComponent.LicenseModel)] = license
            }).Render();
            op.IsScrolling = true;
            await DialogService.Show(op);
        }

        private async Task EditBatchLicenseBtn()
        {
            var op = new DialogOption()
            {
                Title = "编辑证照",
                ShowFooter = false
            };
            op.BodyTemplate = BootstrapDynamicComponent.CreateComponent<Batch.LicenseComponent>(new Dictionary<string, object?>
            {
                [nameof(Batch.LicenseComponent.OnClose)] = new Action(async () => await op.CloseDialogAsync()),
                [nameof(Batch.LicenseComponent.DocStatus)] = DocStatus.View,
                [nameof(Batch.LicenseComponent.UserId)] = UserId,
                [nameof(Batch.LicenseComponent.LicenseModel)] = SelectedBatchLicenses.FirstOrDefault()
            }).Render();
            op.IsScrolling = true;
            await DialogService.Show(op);
        }

        private Task<QueryData<BatchLicense>> OnBatchLicenseQueryAsync(QueryPageOptions options)
        {
            if (IsUnauth)
                return Task.FromResult(new QueryData<BatchLicense>() { });

            IsAutoRefresh = false;
            StateHasChanged();
            BatchLicenses = BatchService.GetLicenses();
            var searchModel = (BatchSearchModel)options.SearchModel;
            //var searchModel = new SearchModel();

            // 处理快速搜索条件
            if (!string.IsNullOrEmpty(options.SearchText))
                BatchLicenses = BatchLicenses.Where(i => (i.Name?.Contains(options.SearchText, StringComparison.OrdinalIgnoreCase) ?? false)
                || (i.LId?.Contains(options.SearchText, StringComparison.OrdinalIgnoreCase) ?? false));

            // 处理自定义搜索条件
            if (!string.IsNullOrEmpty(searchModel.LicenseIdOrName))
                BatchLicenses = BatchLicenses.Where(i => (i.Name?.Contains(searchModel.LicenseIdOrName, StringComparison.OrdinalIgnoreCase) ?? false)
                || (i.LId?.Contains(searchModel.LicenseIdOrName, StringComparison.OrdinalIgnoreCase) ?? false));

            //if (!string.IsNullOrEmpty(searchModel.IdOrName))
            //    BatchLicenses = BatchLicenses.Where(i => (i.BatchId?.Contains(searchModel.IdOrName, StringComparison.OrdinalIgnoreCase) ?? false));
            if (!string.IsNullOrEmpty(searchModel.IdOrName))
            {
                var batch = BatchService.GetByNumber(searchModel.IdOrName);
                if (batch != null && batch.Any())
                    BatchLicenses = BatchLicenses.Where(i => batch.Any(b => b.Id == i.BatchId));
                else
                    BatchLicenses = BatchLicenses.Where(i => i.BatchId?.Contains(searchModel.IdOrName, StringComparison.OrdinalIgnoreCase) ?? false);
            }
            //if (searchModel.Type != null)
            //    BatchLicenses = BatchLicenses.Where(i => i.Type == searchModel.Type);

            if (searchModel.SearchDate != null && searchModel.SearchDate.Start != null)
                BatchLicenses = BatchLicenses.Where(i => i.CreatedOn >= searchModel.SearchDate.Start && i.CreatedOn <= searchModel.SearchDate.End);

            // 过滤
            var isFiltered = false;
            if (options.Filters.Any())
            {
                BatchLicenses = BatchLicenses.Where(options.Filters.GetFilterFunc<BatchLicense>());
                isFiltered = true;
            }

            // 排序
            var isSorted = false;
            if (!string.IsNullOrEmpty(options.SortName))
            {
                if (options.SortOrder == SortOrder.Asc)
                    BatchLicenses = BatchLicenses.OrderBy(g => SharedService.GetPropertyValue(g, options.SortName));
                else if (options.SortOrder == SortOrder.Desc)
                    BatchLicenses = BatchLicenses.OrderByDescending(g => SharedService.GetPropertyValue(g, options.SortName));
                else
                    BatchLicenses = BatchLicenses.OrderByDescending(g => g.LastModifiedOn);
                isSorted = true;
            }

            // 设置记录总数
            var total = BatchLicenses.Count();

            // 内存分页
            BatchLicenses = BatchLicenses.Skip((options.PageIndex - 1) * options.PageItems).Take(options.PageItems).ToList();

            return Task.FromResult(new QueryData<BatchLicense>()
            {
                Items = BatchLicenses,
                TotalCount = total,
                IsSorted = isSorted,
                IsFiltered = isFiltered,
                IsSearch = options.CustomerSearches.Any() || !string.IsNullOrEmpty(options.SearchText),
                IsAdvanceSearch = options.CustomerSearches.Any()
            });
        }

        private async Task ExportBatchLicenses()
        {
            try
            {
                var exportList = BatchService.GetLicensesExport(SelectedBatchLicenses);
                exportList.ForEach(o =>
                {
                    var typeName = GetLicenseTypeName(o.Type, "batch");
                    if (!string.IsNullOrEmpty(typeName))
                        o.Type = typeName;
                    o.BatchId = BatchService.Get(o.BatchId)?.BId;
                });
                var fileName = $"BatchLicense_{DateTime.Now.ToString("yyMMddHHmmss")}.xls";
                var filePathString = Path.Combine(SharedService.GetConfig("exportPath"), fileName);
                var filePath = excelHelper.ExportToExcel(exportList, "BatchLicense", filePathString, ".xls");
                using var stream = File.OpenRead(filePath);
                await DownloadService.DownloadFromStreamAsync(fileName, stream);
                await MessageService.Show(new MessageOption()
                {
                    Content = "导出成功",
                    Icon = "fa-solid fa-circle-info",
                    Color = Color.Success,
                    ShowDismiss = true
                });
            }
            catch (FileNotFoundException)
            {
                await MessageService.Show(new MessageOption()
                {
                    Content = "导出时发生错误，请重试",
                    Icon = "fa-solid fa-circle-error",
                    Color = Color.Danger,
                    ShowDismiss = true
                });
            }
        }

        private Task BatchLicenseSelectChanged(List<BatchLicense> SelectBatchLicenses)
        {
            SelectedBatchLicenses = SelectBatchLicenses;
            StateHasChanged();
            return Task.CompletedTask;
        }
        #endregion

        #region 供应商证照
        private async Task EditSupplierLicense(SupplierLicense license)
        {
            var op = new DialogOption()
            {
                Title = "编辑证照",
                ShowFooter = false
            };
            op.BodyTemplate = BootstrapDynamicComponent.CreateComponent<Supplier.LicenseComponent>(new Dictionary<string, object?>
            {
                [nameof(Supplier.LicenseComponent.OnClose)] = new Action(async () => await op.CloseDialogAsync()),
                [nameof(Supplier.LicenseComponent.DocStatus)] = DocStatus.View,
                [nameof(Supplier.LicenseComponent.UserId)] = UserId,
                [nameof(Supplier.LicenseComponent.LicenseModel)] = license
            }).Render();
            op.IsScrolling = true;
            await DialogService.Show(op);
        }

        private async Task EditSupplierLicenseBtn()
        {
            var op = new DialogOption()
            {
                Title = "编辑证照",
                ShowFooter = false
            };
            op.BodyTemplate = BootstrapDynamicComponent.CreateComponent<Supplier.LicenseComponent>(new Dictionary<string, object?>
            {
                [nameof(Supplier.LicenseComponent.OnClose)] = new Action(async () => await op.CloseDialogAsync()),
                [nameof(Supplier.LicenseComponent.DocStatus)] = DocStatus.View,
                [nameof(Supplier.LicenseComponent.UserId)] = UserId,
                [nameof(Supplier.LicenseComponent.LicenseModel)] = SelectedSupplierLicenses.FirstOrDefault()
            }).Render();
            op.IsScrolling = true;
            await DialogService.Show(op);
        }

        private Task<QueryData<SupplierLicense>> OnSupplierLicenseQueryAsync(QueryPageOptions options)
        {
            if (IsUnauth)
                return Task.FromResult(new QueryData<SupplierLicense>() { });

            IsAutoRefresh = false;
            StateHasChanged();
            SupplierLicenses = SupplierService.GetLicenses();
            var searchModel = (SupplierSearchModel)options.SearchModel;
            //var searchModel = new SearchModel();

            // 处理快速搜索条件
            if (!string.IsNullOrEmpty(options.SearchText))
                SupplierLicenses = SupplierLicenses.Where(i => (i.Name?.Contains(options.SearchText, StringComparison.OrdinalIgnoreCase) ?? false)
                || (i.LId?.Contains(options.SearchText, StringComparison.OrdinalIgnoreCase) ?? false));

            // 处理自定义搜索条件
            if (!string.IsNullOrEmpty(searchModel.LicenseIdOrName))
                SupplierLicenses = SupplierLicenses.Where(i => (i.Name?.Contains(searchModel.LicenseIdOrName, StringComparison.OrdinalIgnoreCase) ?? false)
                || (i.LId?.Contains(searchModel.LicenseIdOrName, StringComparison.OrdinalIgnoreCase) ?? false));

            //if (!string.IsNullOrEmpty(searchModel.IdOrName))
            //    SupplierLicenses = SupplierLicenses.Where(i => (i.SupplierName?.Contains(searchModel.IdOrName, StringComparison.OrdinalIgnoreCase) ?? false)
            //    || (i.SupplierId?.Contains(searchModel.IdOrName, StringComparison.OrdinalIgnoreCase) ?? false));
            if (!string.IsNullOrEmpty(searchModel.IdOrName))
            {
                var suppliers = SupplierService.GetByCode(searchModel.IdOrName);
                if (suppliers != null && suppliers.Any())
                    SupplierLicenses = SupplierLicenses.Where(i => (i.SupplierName?.Contains(searchModel.IdOrName, StringComparison.OrdinalIgnoreCase) ?? false)
                    || (i.SupplierId == suppliers.FirstOrDefault().Id));
                else
                    SupplierLicenses = SupplierLicenses.Where(i => (i.SupplierName?.Contains(searchModel.IdOrName, StringComparison.OrdinalIgnoreCase) ?? false)
                    || (i.SupplierId?.Contains(searchModel.IdOrName, StringComparison.OrdinalIgnoreCase) ?? false));
            }

            if (!string.IsNullOrEmpty(searchModel.Type))
                SupplierLicenses = SupplierLicenses.Where(i => i.Type == searchModel.Type);

            if (searchModel.SearchDate != null && searchModel.SearchDate.Start != null)
                SupplierLicenses = SupplierLicenses.Where(i => i.CreatedOn >= searchModel.SearchDate.Start && i.CreatedOn <= searchModel.SearchDate.End);

            // 过滤
            var isFiltered = false;
            if (options.Filters.Any())
            {
                SupplierLicenses = SupplierLicenses.Where(options.Filters.GetFilterFunc<SupplierLicense>());
                isFiltered = true;
            }

            // 排序
            var isSorted = false;
            if (!string.IsNullOrEmpty(options.SortName))
            {
                if (options.SortOrder == SortOrder.Asc)
                    SupplierLicenses = SupplierLicenses.OrderBy(g => SharedService.GetPropertyValue(g, options.SortName));
                else if (options.SortOrder == SortOrder.Desc)
                    SupplierLicenses = SupplierLicenses.OrderByDescending(g => SharedService.GetPropertyValue(g, options.SortName));
                else
                    SupplierLicenses = SupplierLicenses.OrderByDescending(g => g.LastModifiedOn);
                isSorted = true;
            }

            // 设置记录总数
            var total = SupplierLicenses.Count();

            // 内存分页
            SupplierLicenses = SupplierLicenses.Skip((options.PageIndex - 1) * options.PageItems).Take(options.PageItems).ToList();

            return Task.FromResult(new QueryData<SupplierLicense>()
            {
                Items = SupplierLicenses,
                TotalCount = total,
                IsSorted = isSorted,
                IsFiltered = isFiltered,
                IsSearch = options.CustomerSearches.Any() || !string.IsNullOrEmpty(options.SearchText),
                IsAdvanceSearch = options.CustomerSearches.Any()
            });
        }

        private async Task ExportSupplierLicenses()
        {
            try
            {
                var exportList = SupplierService.GetLicensesExport(SelectedSupplierLicenses);
                exportList.ForEach(o =>
                {
                    var typeName = GetLicenseTypeName(o.Type, "supplier");
                    if (!string.IsNullOrEmpty(typeName))
                        o.Type = typeName;
                    o.SupplierId = SupplierService.Get(o.SupplierId)?.SId;
                });
                var fileName = $"SupplierLicense_{DateTime.Now:yyMMddHHmmss}.xls";
                var filePathString = Path.Combine(SharedService.GetConfig("exportPath"), fileName);
                var filePath = excelHelper.ExportToExcel(exportList, "SupplierLicense", filePathString, ".xls");
                using var stream = File.OpenRead(filePath);
                await DownloadService.DownloadFromStreamAsync(fileName, stream);
                await MessageService.Show(new MessageOption()
                {
                    Content = "导出成功",
                    Icon = "fa-solid fa-circle-info",
                    Color = Color.Success,
                    ShowDismiss = true
                });
            }
            catch (FileNotFoundException)
            {
                await MessageService.Show(new MessageOption()
                {
                    Content = "导出时发生错误，请重试",
                    Icon = "fa-solid fa-circle-error",
                    Color = Color.Danger,
                    ShowDismiss = true
                });
            }
        }

        private Task SupplierLicenseSelectChanged(List<SupplierLicense> SelectLicenses)
        {
            SelectedSupplierLicenses = SelectLicenses;
            StateHasChanged();
            return Task.CompletedTask;
        }
        #endregion

        #region 生产商证照
        private async Task EditManufacturerLicense(ManufacturerLicense license)
        {
            var op = new DialogOption()
            {
                Title = "编辑证照",
                ShowFooter = false
            };
            op.BodyTemplate = BootstrapDynamicComponent.CreateComponent<Manufacturer.LicenseComponent>(new Dictionary<string, object?>
            {
                [nameof(Manufacturer.LicenseComponent.OnClose)] = new Action(async () => await op.CloseDialogAsync()),
                [nameof(Manufacturer.LicenseComponent.DocStatus)] = DocStatus.View,
                [nameof(Manufacturer.LicenseComponent.UserId)] = UserId,
                [nameof(Manufacturer.LicenseComponent.LicenseModel)] = license
            }).Render();
            op.IsScrolling = true;
            await DialogService.Show(op);
        }

        private async Task EditManufacturerLicenseBtn()
        {
            var op = new DialogOption()
            {
                Title = "编辑证照",
                ShowFooter = false
            };
            op.BodyTemplate = BootstrapDynamicComponent.CreateComponent<Manufacturer.LicenseComponent>(new Dictionary<string, object?>
            {
                [nameof(Manufacturer.LicenseComponent.OnClose)] = new Action(async () => await op.CloseDialogAsync()),
                [nameof(Manufacturer.LicenseComponent.DocStatus)] = DocStatus.View,
                [nameof(Manufacturer.LicenseComponent.UserId)] = UserId,
                [nameof(Manufacturer.LicenseComponent.LicenseModel)] = SelectedManufacturerLicenses.FirstOrDefault()
            }).Render();
            op.IsScrolling = true;
            await DialogService.Show(op);
        }

        private Task<QueryData<ManufacturerLicense>> OnManufacturerLicenseQueryAsync(QueryPageOptions options)
        {
            if (IsUnauth)
                return Task.FromResult(new QueryData<ManufacturerLicense>() { });

            IsAutoRefresh = false;
            StateHasChanged();
            ManufacturerLicenses = ManufacturerService.GetLicenses();
            var searchModel = (ManufacturerSearchModel)options.SearchModel;
            //var searchModel = new SearchModel();

            // 处理快速搜索条件
            if (!string.IsNullOrEmpty(options.SearchText))
                ManufacturerLicenses = ManufacturerLicenses.Where(i => (i.Name?.Contains(options.SearchText, StringComparison.OrdinalIgnoreCase) ?? false)
                || (i.LId?.Contains(options.SearchText, StringComparison.OrdinalIgnoreCase) ?? false));

            // 处理自定义搜索条件
            if (!string.IsNullOrEmpty(searchModel.LicenseIdOrName))
                ManufacturerLicenses = ManufacturerLicenses.Where(i => (i.Name?.Contains(searchModel.LicenseIdOrName, StringComparison.OrdinalIgnoreCase) ?? false)
                || (i.LId?.Contains(searchModel.LicenseIdOrName, StringComparison.OrdinalIgnoreCase) ?? false));

            //if (!string.IsNullOrEmpty(searchModel.IdOrName))
            //    ManufacturerLicenses = ManufacturerLicenses.Where(i => (i.ManufacturerName?.Contains(searchModel.IdOrName, StringComparison.OrdinalIgnoreCase) ?? false)
            //    || (i.ManufacturerId?.Contains(searchModel.IdOrName, StringComparison.OrdinalIgnoreCase) ?? false));
            if (!string.IsNullOrEmpty(searchModel.IdOrName))
            {
                var manufacturer = ManufacturerService.GetByCode(searchModel.IdOrName);
                if (manufacturer != null && !string.IsNullOrEmpty(manufacturer.Id))
                    ManufacturerLicenses = ManufacturerLicenses.Where(i => (i.ManufacturerName?.Contains(searchModel.IdOrName, StringComparison.OrdinalIgnoreCase) ?? false)
                    || (i.ManufacturerId == manufacturer.Id));
                else
                    ManufacturerLicenses = ManufacturerLicenses.Where(i => (i.ManufacturerName?.Contains(searchModel.IdOrName, StringComparison.OrdinalIgnoreCase) ?? false)
                    || (i.ManufacturerId?.Contains(searchModel.IdOrName, StringComparison.OrdinalIgnoreCase) ?? false));
            }

            //if (searchModel.Type != null)
            //    ManufacturerLicenses = ManufacturerLicenses.Where(i => i.Type == searchModel.Type);
            if (!string.IsNullOrEmpty(searchModel.LicenseType))
                ManufacturerLicenses = ManufacturerLicenses.Where(i => i.Type == searchModel.LicenseType);

            if (searchModel.SearchDate != null && searchModel.SearchDate.Start != null)
                ManufacturerLicenses = ManufacturerLicenses.Where(i => i.CreatedOn >= searchModel.SearchDate.Start && i.CreatedOn <= searchModel.SearchDate.End);

            // 过滤
            var isFiltered = false;
            if (options.Filters.Any())
            {
                ManufacturerLicenses = ManufacturerLicenses.Where(options.Filters.GetFilterFunc<ManufacturerLicense>());
                isFiltered = true;
            }

            // 排序
            var isSorted = false;
            if (!string.IsNullOrEmpty(options.SortName))
            {
                if (options.SortOrder == SortOrder.Asc)
                    ManufacturerLicenses = ManufacturerLicenses.OrderBy(g => SharedService.GetPropertyValue(g, options.SortName));
                else if (options.SortOrder == SortOrder.Desc)
                    ManufacturerLicenses = ManufacturerLicenses.OrderByDescending(g => SharedService.GetPropertyValue(g, options.SortName));
                else
                    ManufacturerLicenses = ManufacturerLicenses.OrderByDescending(g => g.LastModifiedOn);
                isSorted = true;
            }

            // 设置记录总数
            var total = ManufacturerLicenses.Count();

            // 内存分页
            ManufacturerLicenses = ManufacturerLicenses.Skip((options.PageIndex - 1) * options.PageItems).Take(options.PageItems).ToList();

            return Task.FromResult(new QueryData<ManufacturerLicense>()
            {
                Items = ManufacturerLicenses,
                TotalCount = total,
                IsSorted = isSorted,
                IsFiltered = isFiltered,
                IsSearch = options.CustomerSearches.Any() || !string.IsNullOrEmpty(options.SearchText),
                IsAdvanceSearch = options.CustomerSearches.Any()
            });
        }

        private async Task ExportManufacturerLicenses()
        {
            try
            {
                var exportList = ManufacturerService.GetLicensesExport(SelectedManufacturerLicenses);
                exportList.ForEach(o =>
                {
                    var typeName = GetLicenseTypeName(o.Type, "manufacturer");
                    if (!string.IsNullOrEmpty(typeName))
                        o.Type = typeName;
                    o.ManufacturerId = ManufacturerService.Get(o.ManufacturerId)?.MId;
                });
                var fileName = $"ManufacturerLicense_{DateTime.Now.ToString("yyMMddHHmmss")}.xls";
                var filePathString = Path.Combine(SharedService.GetConfig("exportPath"), fileName);
                var filePath = excelHelper.ExportToExcel(exportList, "ManufacturerLicense", filePathString, ".xls");
                using var stream = File.OpenRead(filePath);
                await DownloadService.DownloadFromStreamAsync(fileName, stream);
                await MessageService.Show(new MessageOption()
                {
                    Content = "导出成功",
                    Icon = "fa-solid fa-circle-info",
                    Color = Color.Success,
                    ShowDismiss = true
                });
            }
            catch (FileNotFoundException)
            {
                await MessageService.Show(new MessageOption()
                {
                    Content = "导出时发生错误，请重试",
                    Icon = "fa-solid fa-circle-error",
                    Color = Color.Danger,
                    ShowDismiss = true
                });
            }
        }

        private Task ManufacturerLicenseSelectChanged(List<ManufacturerLicense> SelectLicenses)
        {
            SelectedManufacturerLicenses = SelectLicenses;
            StateHasChanged();
            return Task.CompletedTask;
        }
        #endregion

        private void RefreshData()
        {
            //ProductLicenseCount = ProductService.GetLicenses().Count.ToString();
            //SupplierLicenseCount = SupplierService.GetLicenses().Count.ToString();
            //ManufacturerLicenseCount = ManufacturerService.GetLicenses().Count.ToString();
            //BatchLicenseCount = BatchService.GetLicenses().Count.ToString();
            ProductLicenseCount = ProductService.GetLicenseCount().ToString();
            SupplierLicenseCount = SupplierService.GetLicenseCount().ToString();
            ManufacturerLicenseCount = ManufacturerService.GetLicenseCount().ToString();
            BatchLicenseCount = BatchService.GetLicenseCount().ToString();
            IsAutoRefresh = true;
            StateHasChanged();
        }

        private string GetLicenseTypeName(string id, string module)
        {
            var licenseTypes = BatchService.GetLicenseType();
            if (licenseTypes != null && licenseTypes.Any())
            {
                var licenseType = licenseTypes.FirstOrDefault(predicate: l => l.TypeId == id && l.Module == module);
                if (licenseType != null)
                    return licenseType.TypeName;
            }
            return string.Empty;
        }
    }
}

